// ByteStreamHandler.cpp
#include "ByteStreamHandler.h"
#include <fstream>
#include <iostream>

bool ByteStreamHandler::writeBytes(const std::string& filename, std::string str) {
    // 将std::string转换为std::vector<char>以便写入
    std::vector<char> data(str.begin(), str.end());

    return ByteStreamHandler::writeBytes(filename,data);
}

bool ByteStreamHandler::writeBytes(const std::string& filename, const std::vector<char>& data) {
    // 获取文件路径对象
    std::filesystem::path path(filename);

    // 创建文件所在的目录（如果它们不存在）
    if (path.has_parent_path()) {
        std::filesystem::create_directories(path.parent_path());
    }

    std::ofstream out(filename, std::ios::binary);
    if (!out) {
        std::cerr << "Cannot open file for writing: " << filename << std::endl;
        return false;
    }
    out.write(data.data(), data.size());
    return out.good();
}

std::unique_ptr<std::vector<char>> ByteStreamHandler::readBytes(const std::string& filename) {
    std::ifstream in(filename, std::ios::binary);
    if (!in) {
        std::cerr << "Cannot open file for reading: " << filename << std::endl;
        return nullptr;
    }

    // Move to the end of the file to determine its size
    in.seekg(0, std::ios::end);
    size_t size = in.tellg() * 2;
    in.seekg(0, std::ios::beg);

    // Read the contents of the file
    auto buffer = std::make_unique<std::vector<char>>(size);
    in.read(buffer->data(), size);

    return buffer;
}
